package com.mfnote.view.hand;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.ColorDrawable;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TimePicker;
import android.widget.Toast;

import com.mfnote.adapter.HandWritingAdapter;
import com.mfnote.db.dao.HandDao;
import com.mfnote.model.HandEntity;
import com.mfnote.model.HandInsertEntity;
import com.mfnote.util.MyReceiver;
import com.mfnote.util.RandomUtils;
import com.mfnote.util.ShareUtil;
import com.mfnote.util.StringUtils;
import com.mfnote.view.R;
import com.mfnote.view.R.drawable;
import com.mfnote.view.R.id;
import com.mfnote.view.R.layout;

public class HandWritingActivity extends Activity implements
		OnItemClickListener {
	private GridView handwriting_gv_menu = null;
	private LinearLayout newwriting_ll_edittext = null;
	public LinearLayout newwriting_ll_view = null;

	private PopupWindow popMore = null;

	private View moreView = null;

	private LinearLayout handwriting_ll_draw = null;
	private LinearLayout handwriting_ll_remain = null;
	private LinearLayout handwriting_ll_share = null;
	
	private EditText handwriting_et_title_name = null;

	// 显示缩写笔迹文字
	private NewEditText newEditText = null;

	private HandWritingView handWiew = null;

	public boolean showHandView = true;


	// 插入的图片
	private List<HandInsertEntity> entitys = null;
	// 记录所有插入的数据的imageName
	private StringBuffer insertString = null;

	private final String strBlank = "insert_an_blank.png";
	private final String strNextLine = "insert_nextline.png";
	private String time = null;

	private String imagePath = "";

	// 是否可以删除文件中的图片
	private boolean isCanDeleteBitmap = false;

	private boolean isNeedSaveAgain = false;
	
	//是否点击过保存
	private boolean isOnSaveClick = false;
	// 保存的title
	private String title = "";
	// 是否保存过
	private boolean isSaved = false;
	// 跳转带来的数据
	private HashMap<String, Object> map = null;

	private HandDao handdao = null;

	private Display display = null;

	private Calendar calendar = null;
	
	//当前光标的位置
	public  int currentCursorIndex = 0;
	// 记录插入的次数包括空格、换行
	private int insertAllCount = 0;
	//记录插入点前面有字符串的长度
	public int prepLength = 0;
	private AlertDialog alertDlgIsDel; //长按记录弹出删除提示框
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 10:
				// 新建是发来的消息
				HandInsertEntity entity = (HandInsertEntity) msg.obj;
				Bitmap bit = entity.getBitmap();
				String bitmapName = entity.getBitmapName();
				if(currentCursorIndex==insertAllCount){
					//光标在最后位置直接插入
				    newEditText.insertBitmap(bit);
					insertString.append(bitmapName);
					entitys.add(entity);
				}else{
					//在当前光标的位置+1插入图片
					newEditText.setText("");
					String images = StringUtils.insertString(insertString.toString(), bitmapName, currentCursorIndex);
					Log.d("images", images);
					init(images);
					Log.d("Spannable", (currentCursorIndex+1)+"");
					//Selection.setSelection((Spannable)(CharSequence)newEditText.getText(), (currentCursorIndex+1)*5);
					prepLength+= 5;
					newEditText.setSelection(prepLength);
					int n = newEditText.getText().toString().length();
					Log.d("newEditText", "插入的位置: "+prepLength+"字符串的长度: "+n);
					
				}
				isSaved = false;
				isNeedSaveAgain = true;
				isOnSaveClick  = false;
				insertAllCount++;
				currentCursorIndex++;
				break;
			case 11:
				// 点击item跳转过来的
				init(imagePath);
				currentCursorIndex = insertAllCount;
				break;
			}

			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.handwriting);

		handwriting_gv_menu = (GridView) findViewById(R.id.handwriting_gv_menu);
		handwriting_gv_menu.setSelector(new ColorDrawable(Color.TRANSPARENT));  //去掉自身自带的按下背景效果
		newwriting_ll_edittext = (LinearLayout) findViewById(R.id.newwriting_ll_edittext);
		newwriting_ll_view = (LinearLayout) findViewById(R.id.newwriting_ll_view);

		moreView = LayoutInflater.from(this).inflate(
				R.layout.handwriting_more_popup, null);
		handwriting_ll_draw = (LinearLayout) moreView
				.findViewById(R.id.handwriting_ll_draw);
		handwriting_ll_remain = (LinearLayout) moreView
				.findViewById(R.id.handwriting_ll_remain);
		handwriting_ll_share = (LinearLayout) moreView
				.findViewById(R.id.handwriting_ll_share);
		handwriting_et_title_name  =(EditText) findViewById(R.id.handwriting_et_title_name);

		display = getWindowManager().getDefaultDisplay();

		handwriting_gv_menu.setAdapter(new HandWritingAdapter(this));

		newEditText = new NewEditText(this);
		// TODO 设置大小
		newEditText.setWidth(display.getWidth());
		newEditText.setHeight(display.getHeight());
		newEditText.setGravity(Gravity.TOP | Gravity.LEFT);
		// 设置背景,隐藏边框
		newEditText.setBackgroundColor(Color.WHITE);
		// 隐藏newEditText光标
		//newEditText.setCursorVisible(false);
		newEditText.setEnabled(true);
		newEditText.requestFocus();
		
		newwriting_ll_edittext.addView(newEditText);

		handwriting_gv_menu.setOnItemClickListener(this);

		entitys = new ArrayList<HandInsertEntity>();

		insertString = new StringBuffer();
		handdao = new HandDao(this);

		map = (HashMap<String, Object>) getIntent().getSerializableExtra("map");
		// Log.d("map_hand", map.get("title").toString());
		if (map == null) {
			// 不做任何处理,相当于新建
			// 可以删除文件中的图片
			isCanDeleteBitmap = true;
		} else {
			// 从item点击来的
			isSaved = true;
			// 不能删除文件中的图片
			isCanDeleteBitmap = false;
			title = (String) map.get("title");
			imagePath = (String) map.get("imagePath");
			time = (String) map.get("time");
			int flag = (Integer) map.get("flag");
			Log.d("map", title + "--" + imagePath + "==" + time + "--" + flag);
			
			handwriting_et_title_name.setText(title);
			Message msg = new Message();
			msg.what = 11;
			handler.sendMessage(msg);
		}

	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);

		newwriting_ll_view.removeAllViews();
		handWiew = new HandWritingView(this, handler);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT, 1);
		// 设置handWiew距离父控件的边距离
		params.setMargins(10, 10, 10, 10);
		handWiew.setLayoutParams(params);
		handWiew.setFocusable(true);

		// 屏蔽editText的键盘效果
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(newEditText.getWindowToken(), 0);

		newwriting_ll_view.addView(handWiew);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (showHandView) {
				newwriting_ll_view.setVisibility(View.GONE);
				showHandView = false;
			} else {
				// 自动保存
				if(!isOnSaveClick){
					saveCheck();
				}
				//saveCheck();
				Log.d("save", "------save----");
				// 跳转到
				Intent intent = new Intent(this, HandActivity.class);
				startActivity(intent);
				this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
			}
		}
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		switch (position) {
		case 0:
			Log.d("onItemClick", "onItemClick--0");
			// 添加换行
			if(insertAllCount==currentCursorIndex){
				//在最后添加
				newEditText.insertNextLine();
			    insertString.append(strNextLine);
			}else{
				newEditText.setText("");
				String images = StringUtils.insertString(insertString.toString(), strNextLine, currentCursorIndex);
				Log.d("nextLine", images);
				init(images);
				prepLength+= 2;
				newEditText.setSelection(prepLength);
			}
			insertAllCount++;
			currentCursorIndex++;
			isNeedSaveAgain = true;
			isOnSaveClick = false;
			isSaved = false;
			break;
		case 1:
			Log.d("onItemClick", "onItemClick--1");
			// 添加空格
			if(insertAllCount==currentCursorIndex){
				newEditText.insertBlank();
			    insertString.append(strBlank);
			}else{
				newEditText.setText("");
				String blankImages = StringUtils.insertString(insertString.toString(), strBlank, currentCursorIndex);
				Log.d("blank", blankImages);
				init(blankImages);
				prepLength+= 1;
				newEditText.setSelection(prepLength);
			}

			insertAllCount++;
			currentCursorIndex++;
			isSaved  = false;
			isNeedSaveAgain = true;
			isOnSaveClick  = false;
			break;
		case 2:
			Log.d("onItemClick", "onItemClick--2");
			// 撤销
			repeal();
			isSaved = false;
			isNeedSaveAgain = true;
			isOnSaveClick  = false;
			isSaved = false;
			break;
		case 3:
			Log.d("onItemClick", "onItemClick--3");
			// 保存
			if(!isOnSaveClick){
				saveCheck();
				isSaved = true;
				isOnSaveClick = true;
			}
			//保存完之后跳回手写列表界面
			Intent intent = new Intent(this,HandActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
			break;
		case 4:
			Log.d("onItemClick", "onItemClick--4");
			// 更多
			showMorePopWindow(parent);
			break;

		}

	}
    
	/** 撤销 删除操作**/
	private void repeal() {
		if(currentCursorIndex<=0){
			//如果光标在0的位置则不作任何处理
			return;
		}
		int currentInsert = 0;
		int currentBitmapInsert = 0;
		String names = insertString.toString();
		// 清空newEditText
		newEditText.setText("");
		// 清空insertString中的数据,重新赋值
		insertString.delete(0, insertString.length());
		Log.d("names", names + "--------");
		Pattern pattern = Pattern.compile("\\w+[.][p][n][g]");
		Matcher matcher = pattern.matcher(names);
        String beforeStr = "";
		while (matcher.find()) {
			String find = matcher.group(); 
			currentInsert++;
			if(currentInsert==currentCursorIndex){
				beforeStr = newEditText.getText().toString();
				
                if(strNextLine.equals(find)){
					//光标的前面是换行
					prepLength-=2;
				}else if(strBlank.equals(find)){
					//光标的前面是空格
					prepLength-=1;
				}else{
					//光标的前面是图片,从entitys中移除当前位置的数据
					Log.d("last", "====last======" + find);
					Log.d("last", "====last======" + (entitys.size() - 1));

					if (isCanDeleteBitmap) {
						// 删除文件中的图片
						File file = new File("/mnt/sdcard/MFNote/hand/"
								+ entitys.get(entitys.size() - 1)
										.getBitmapName());
						if (file.exists()) {
							// 删除文件
							file.delete();
						}
					}
					entitys.remove(currentBitmapInsert);
					prepLength-=5;
					
				}
				continue;
			}
			
			if (currentInsert <=insertAllCount) {
				Log.d("count", "=========");
				Log.d("find", "=========" + find + "===");
				if (find.equals(strBlank)) {
					// 插入空格
					newEditText.insertBlank();
					insertString.append(strBlank);
					Log.d("blank", "blank");
				} else if (find.equals(strNextLine)) {
					// 插入换行
					newEditText.insertNextLine();
					insertString.append(strNextLine);
				} else if(find.contains("png")){
					// 插入图片
					newEditText.insertBitmap(entitys.get(currentBitmapInsert)
							.getBitmap());
					insertString.append(entitys.get(currentBitmapInsert)
							.getBitmapName());
					currentBitmapInsert++;
				}
			}
		}
		// 插入的数据的总次数减一
		if (insertAllCount > 0) {
			insertAllCount--;
		}
		if(currentCursorIndex>0){
			currentCursorIndex--;
			newEditText.setSelection(beforeStr.length());
		}
	}

	/** 保存数据到数据库中 **/
	private void save() {
		if (insertAllCount == 0) {
			//Toast.makeText(this, "空数据,不需要保存", Toast.LENGTH_SHORT).show();
			return;
		}
		
		//判断edit_title中是否有数据
		String edit_title = handwriting_et_title_name.getText().toString().trim();
		
		
		String newtitle = createFileName();
		if(!edit_title.equals("")&&edit_title!=null){
			newtitle = edit_title;
			Log.d("edit_title", "---"+edit_title);
		}

		// 需要保存的数据有insertString
		HandEntity handEntity = new HandEntity();
		handEntity.setFlag(1);
		handEntity.setImagePath(insertString.toString());
		Log.d("insertString_", insertString.toString());
		handEntity.setTitle(newtitle);
		handEntity.setTime(time);
		handdao.insertHand(handEntity);
		isSaved = true;
	}

	/** 判断是否需要保存以及删除旧的数据 **/
	private void saveCheck() {
		//判断edit_title中是否有数据
		String edit_title = handwriting_et_title_name.getText().toString().trim();
		if(!edit_title.equals(title)){
			isSaved = false;
			isNeedSaveAgain = true;
			Log.d("isSave", isSaved+"--");
		}
		if (map != null && isNeedSaveAgain) {
			// 删除原来的item;
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("title", title);
			// 根据标题删除
			handdao.deleteHand(hashMap);
			
		}
		if (!isSaved) {
			save();
		}
		
	}

	/** 获得一个时间值的文件名 **/
	private String createFileName() {
		String fileName = "";
		Date date = new Date(System.currentTimeMillis()); // 系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
		fileName = dateFormat.format(date);
		dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = dateFormat.format(date);
		return fileName;
	}

	/** 加载所有的图片 **/
	private void init(String imagePath) {
		insertAllCount = 0;
		entitys.removeAll(entitys);
		insertString.delete(0, insertString.toString().length());
		
		String names = imagePath;
		Pattern pattern = Pattern.compile("\\w+[.][p][n][g]");
		Matcher matcher = pattern.matcher(names);
		while (matcher.find()) {
			String find = matcher.group();
			if (find.equals(strBlank)) {
				// 插入空格
				newEditText.insertBlank();
				insertString.append(strBlank);
				Log.d("blank", "blank");
				insertAllCount++;
			} else if (find.equals(strNextLine)) {
				// 插入换行
				newEditText.insertNextLine();
				insertString.append(strNextLine);
				insertAllCount++;
			} else {
				String bitmapName = find;
				File file = new File("/mnt/sdcard/MFNote/hand/" + bitmapName);
				if (file.exists()) {
					// 加载图片
					Bitmap bitmap = initBitmap(file);
					Log.d("bitmap", "bitmap");
					// 插入图片
					newEditText.insertBitmap(bitmap);

					Log.d("bitmapName", bitmapName);
					HandInsertEntity entity = new HandInsertEntity(bitmap,
							bitmapName);
					insertString.append(bitmapName);
					insertAllCount++;
					entitys.add(entity);
				}
			}
			
			
		}

	}

	/** 获取bitmap **/
	private Bitmap initBitmap(File file) {
		Bitmap bitmap = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			bitmap = BitmapFactory.decodeStream(fis);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	/** 显示更多的PopWindow **/
	private void showMorePopWindow(View parent) {
		handwriting_ll_draw.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("draw", "------draw-----");
				popMore.dismiss();
				// 手绘图形
				// 首先保存当前界面的数据,再跳转到NewHandActivity;
				saveCheck();
				Intent intent = new Intent(HandWritingActivity.this,
						NewHandActivity.class);
				HandWritingActivity.this.startActivity(intent);
				finish();
				overridePendingTransition(R.anim.push_right_in,
						R.anim.push_left_out);
			}
		});
		handwriting_ll_remain.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("remain", "------remain-----");
				popMore.dismiss();
				// 提醒
				openTimePickerDialog();
			}
		});
		handwriting_ll_share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("share", "------share-----");
				popMore.dismiss();
				// 分享
				ShareUtil.share(shot(), "", HandWritingActivity.this);
			}
		});

		if (popMore == null) {
			popMore = new PopupWindow(moreView, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			popMore.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.more_popup_bg_3_item));
		}

		if (!popMore.isShowing()) {
			popMore.showAtLocation(parent, Gravity.BOTTOM | Gravity.RIGHT, 0,
					handwriting_gv_menu.getHeight());
		}
	}

	/** 设置提醒的时间选择 **/
	private void openTimePickerDialog() {
		calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);

		TimePickerDialog dialog = new TimePickerDialog(this,
				new MyTimePickerDialog(), hour, minute, true);
		dialog.setTitle("设置提醒的时间");
		dialog.show();

	}



	/** 设置完时间提醒之后跳回HandActivity **/
	private void saveAndReturn() {
		// 跳转之前判断是否保存过,为保存则保存，否则直接跳转
		saveCheck();
		// 返回到HandActivity
		Intent intent_return = new Intent(HandWritingActivity.this,
				HandActivity.class);
		startActivity(intent_return);
		finish();
		overridePendingTransition(R.anim.push_left_in,
				R.anim.push_right_out);
	}

	/** 分享操作：截屏保存的图片的地址 **/
	private String shot() {
		//分享的图片的name
		String imageName = "";
		Date date = new Date(System.currentTimeMillis()); // 系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
		imageName = dateFormat.format(date)+".png";
		// 判断手写的HandWritingView是否处于不可见状态,是则直接截屏，否则首先设置不可见
		if (showHandView) {
			newwriting_ll_view.setVisibility(View.GONE);
		}
		// 获取当前的手机屏幕的view
		View view = getWindow().getDecorView();
		// 获取状态栏的高度
		Rect rect = new Rect();
		view.getWindowVisibleDisplayFrame(rect);
		int statuesBarHeight = rect.top;
		// 设置截屏的区域
		view.layout(0, 0, display.getWidth(), display.getHeight()
				- handwriting_gv_menu.getHeight());
		// 允许当前窗口保存缓存信息，这样getDrawingCache()才会得到一个bitmap
		view.setDrawingCacheEnabled(true);
		Bitmap bit = Bitmap.createBitmap(view.getDrawingCache());
		Bitmap bitmap = Bitmap.createBitmap(bit, 0, statuesBarHeight, display.getWidth(),
				display.getHeight() - handwriting_gv_menu.getHeight() - statuesBarHeight);
		// TODO 测试用保存
		File file = null;
		try {
			// 保存图片到/mnt/sdcard/MFNote/hand/fen.jpg
			file = new File("/mnt/sdcard/MFNote/hand/"+imageName);
			FileOutputStream fos = new FileOutputStream(file);
			bitmap.compress(CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file.getAbsolutePath().toString();
	}
	
	/** 时间选择对话框 **/
	private class MyTimePickerDialog implements
			TimePickerDialog.OnTimeSetListener {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			// 将自己设置好的时间设置进去
			calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
			calendar.set(Calendar.MINUTE, minute);

			Intent intent = new Intent("com.mfnote.view.handwriting");
			intent.setClass(HandWritingActivity.this, MyReceiver.class);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("title", title);
			map.put("flag", 1);
			map.put("imagePath", insertString.toString());
			map.put("time", time);
			intent.putExtra("map", map);
			int requestCode = RandomUtils.getRequestCode();

			intent.putExtra("requestCode", requestCode);
			PendingIntent pi = PendingIntent.getBroadcast(
					HandWritingActivity.this, requestCode, intent, 0);

			// 设置一个PendingIntent对象，发送广播
			AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
			// 获取AlarmManager对象
			am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi); // 时间到时，执行PendingIntent，只执行一次

			Log.d("dialog", "点击设置后执行....");
			saveAndReturn();
		}
	}
}
